package com.gjintel.framework.register.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.Constant.FileType;
import com.gjintel.framework.projecttype.model.ProjectType;
import com.gjintel.framework.projecttype.service.IProjectTypeService;
import com.gjintel.framework.register.model.DepositCategory;
import com.gjintel.framework.register.model.RegisterCategory;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.framework.util.Rsp;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.util.MD5Lock;
import com.gjintel.sdk.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RequestMapping("/template/register")
@Controller
public class RegisterController {
	@Autowired
	private IRegisterUserService registerUserService;
	@Autowired
	private IProjectTypeService projectTypeService;

	/**
	 * @author shy
	 * @description 投标人注册
	 * @param registerUser
	 * @throws IOException
	 */
	@RequestMapping("/saveRegisterUser")
	@ResponseBody
	@Transactional
	public void SaveRegisterUser(RegisterUser registerUser,HttpServletResponse resp, HttpSession session,String editFlag) throws IOException {
		registerUser.setLoginName(registerUser.getLoginName().trim());
		String result = "";
		if (StringUtil.isEmpty(registerUser.getImage01())){
			result = Constant.NO_IMAGE_01;
		} else if(StringUtil.isEmpty(registerUser.getImage02())){
			result = Constant.NO_IMAGE_02;
		}else if(editFlag==null){//正常注册验证
			List<RegisterUser> sameAccountUser = registerUserService.getSameAccountUser(registerUser.getAccount());
			if(sameAccountUser.size()>0){//相同银行账号
				result= Constant.SAME_ACCOUNT;
			}else{
				List<RegisterUser> registerUsers = this.registerUserService.findRegisterUserByLoginName(registerUser.getLoginName());
				if (registerUsers.size() > 0) {//相同用户名
					result = Constant.REGISTER_REPEAT;
				}else{
					registerUser.setName(registerUser.getLoginName());
					result = this.registerUserService.saveRegisterUser(registerUser);
					session.setAttribute("registerUser", registerUser);
				}
			}

		}else if(editFlag.equals("1")){//用户修改
			List<RegisterUser> sameAccountUser = registerUserService.getSameAccountUserExceptMyself(registerUser.getAccount(),registerUser.getLoginName());
			if(sameAccountUser.size()>0){//相同银行账号
				result= Constant.SAME_ACCOUNT;
			}else{
			registerUser.setName(registerUser.getLoginName());
			registerUser.setFlag(0);
			registerUser.setUpdateTime(new Date());
			this.registerUserService.saveOrUpdate(registerUser);
			this.registerUserService.saveCategory(registerUser.getProjectCategory(), registerUser.getId());
			result=Constant.REGISTER_SUCCESS_UN_COMPLETE;
			session.setAttribute("registerUser", registerUser);
		   }
		}
		resp.getWriter().print(result);
	}

	/**
	 * 未审核登录返回用户信息
	 */
	@RequestMapping("/unRegiserlogin")
	@ResponseBody
	public Rsp getRegisterUserByLoginName(String loginName, String pwd) {
		Rsp rsp = new Rsp();
		rsp = this.registerUserService.getRegisterUserByLoginName(loginName, pwd);
		return rsp;
	}

	/**
	 * @description 根据Id获取注册用户信息
	 * @author shy
	 *
	 */
	@RequestMapping("/getRegister")
	@ResponseBody
	public ModelAndView getRegister(HttpServletRequest resp) {
		String str = resp.getParameter("str");
		String id = resp.getParameter("id");
		ModelAndView mv = new ModelAndView();
		RegisterUser rUser = new RegisterUser();
		rUser = registerUserService.getRegisterById(id);
		Resources resources = new Resources();
		resources = this.registerUserService.get(Resources.class, rUser.getImage01());
		Resources resources2 = new Resources();
		resources2 = this.registerUserService.get(Resources.class, rUser.getImage02());
		Resources resources3 = new Resources();
		resources3 = this.registerUserService.get(Resources.class, rUser.getImage03());
		Resources resources4 = new Resources();
		resources4 = this.registerUserService.get(Resources.class, rUser.getImage04());
		Resources resources5 = new Resources();
		resources5 = this.registerUserService.get(Resources.class, rUser.getImage05());
		String DepositCategoryData = registerUserService.getDepositCategoryName(id);
		mv.addObject("depositCategory", DepositCategoryData);
		mv.addObject("register", rUser);
		mv.addObject("image01", resources);
		mv.addObject("image02", resources2);
		mv.addObject("image03", resources3);
		mv.addObject("image04", resources4);
		mv.addObject("image05", resources5);
		if (str.equals("audit")) {
			mv.setViewName("register/register-audit");
		} else if (str.equals("read")) {
			mv.setViewName("register/register-info");
		}

		return mv;
	}

	/**
	 * @description 根据Id获取注册用户信息
	 * @author shy
	 *
	 */
	@RequestMapping("/registerInfo")
	@ResponseBody
	public ModelAndView registerInfo(HttpServletRequest resp,HttpSession session) {
		User user = (User) session.getAttribute("loginUser");
		String id = user.getRegisterId();
		ModelAndView mv = new ModelAndView();
		RegisterUser rUser = new RegisterUser();
		rUser = registerUserService.getRegisterById(id);
		Resources resources = new Resources();
		resources = this.registerUserService.get(Resources.class, rUser.getImage01());
		Resources resources2 = new Resources();
		resources2 = this.registerUserService.get(Resources.class, rUser.getImage02());
		Resources resources3 = new Resources();
		resources3 = this.registerUserService.get(Resources.class, rUser.getImage03());
		Resources resources4 = new Resources();
		resources4 = this.registerUserService.get(Resources.class, rUser.getImage04());
		Resources resources5 = new Resources();
		resources5 = this.registerUserService.get(Resources.class, rUser.getImage05());
		String DepositCategoryData = registerUserService.getDepositCategoryName(id);
		mv.addObject("depositCategory", DepositCategoryData);
		mv.addObject("register", rUser);
		mv.addObject("image01", resources);
		mv.addObject("image02", resources2);
		mv.addObject("image03", resources3);
		mv.addObject("image04", resources4);
		mv.addObject("image05", resources5);
        mv.setViewName("register/register-info");
		return mv;
	}


	/**
	 * 审核人查看注册人信息
	 *
	 * @throws IOException
	 */
	@RequestMapping("/getRegisterList")
	@ResponseBody
	public void registerList(HttpServletResponse resp, Page page,RegisterUser register,java.sql.Date startTime,java.sql.Date endTime)
			throws IOException {
		endTime=StringUtil.addOneDayDate(endTime, 1);
		List<RegisterUser> registerUsers  = this.registerUserService.getRegisterList(page,register,startTime,endTime);
		if (!page.getResult().isEmpty()) {
			 page.getResult().iterator();

		}
		JSONObject jsonObject = CommUtil.getPageJSONData(page, true);
		resp.getWriter().print(jsonObject);
	}

	/**
	 * 审核人查看注册人信息
	 *
	 * @throws IOException
	 */
	@RequestMapping("/searchList")
	@ResponseBody
	public void searchList(HttpServletRequest request,
			HttpServletResponse resp, Page page) throws IOException {
		String name = new String(request.getParameter("registerName").getBytes(
				"iso8859-1"), "utf-8");
		String loginName = new String(request.getParameter("loginName")
				.getBytes("iso8859-1"), "utf-8");
		String flagTemp = request.getParameter("registerFlag");
		int flag = 4;
		if (!StringUtil.isEmpty(flagTemp)) {
			flag = Integer.parseInt(flagTemp);
		}

		this.registerUserService.searchList(page, name, loginName, flag);
		if (!page.getResult().isEmpty()) {
			page.getResult().iterator();
		}
		JSONObject jsonObject = CommUtil.getPageJSONData(page, true);
		resp.getWriter().print(jsonObject);
	}

	/**
	 * 审核投标人信息
	 *
	 * @throws IOException
	 *
	 */
	@RequestMapping("/audit")
	@ResponseBody
	public JSONObject auditRegister(String registerId, int flag, String reason,
			HttpSession session) throws IOException {
		JSONObject jsonObject = new JSONObject();
		Rsp rsp = new Rsp();
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			rsp.setRows(Constant.UNLOGIN);
			jsonObject = JSONObject.fromObject(rsp);
		} else {
			rsp = this.registerUserService.auditRegister(user, registerId, reason,
					flag);
			jsonObject = JSONObject.fromObject(rsp);
		}
		return jsonObject;

	}

	/**
	 * @description 保存文件
	 * @author shy
	 * @param file
	 * @param relativePath
	 * @param uploadPath
	 * @param resId
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 * @return Resources
	 */
	private Resources saveFile(MultipartFile file, String relativePath,
			String uploadPath, String resId, HttpServletRequest request)
			throws IllegalStateException, IOException {
		String fileName = file.getOriginalFilename();
		if (!StringUtil.isEmpty(fileName)) {
			Resources res = new Resources();
			String exeName = fileName.substring(fileName.lastIndexOf("."),
					fileName.length());
			res.setExeName(exeName);
			res.setFilePath(relativePath);
			res.setFileSize(file.getSize());
			res.setFileType(FileType.PICTURE.toString().toLowerCase());
			res.setOldName(fileName);
			FileResUtil.addFileRes(res); // 保存文件记录
			File newFile = new File(uploadPath, res.getId() + res.getExeName());
			file.transferTo(newFile);
			// 把老数据和文件给与删除
			if (!StringUtil.isEmpty(resId)) {
				FileResUtil.deleteFile(resId, request);
			}
			return res;
		}
		return null;
	}

	/**
	 * @description 文件上传
	 * @author fengya
	 * @date 2016-3-17 上午09:23:26
	 * @return void
	 * @throws IOException
	 * @throws IllegalStateException
	 */

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void uploadPic(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws IllegalStateException, IOException {
		PrintWriter out = response.getWriter();
		RegisterUser rUser = new RegisterUser();
		// rUser=(RegisterUser)session.getAttribute("loginUser");
		// String registerId=rUser.getId();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile1 = multipartRequest.getFileMap().get(
				"image01");
		MultipartFile multipartFile2 = multipartRequest.getFileMap().get(
				"image02");
		MultipartFile multipartFile3 = multipartRequest.getFileMap().get(
				"image03");
		MultipartFile multipartFile4 = multipartRequest.getFileMap().get(
				"image04");
		MultipartFile multipartFile5 = multipartRequest.getFileMap().get(
				"image05");
		String relativePath = null;
		if (multipartFile1 != null) {
			// 得到文件的相对路径
			relativePath = File.separator + multipartFile1.getName()
					+ File.separator;
		} else if (multipartFile2 != null) {
			relativePath = File.separator + multipartFile2.getName()
					+ File.separator;
		} else if (multipartFile3 != null) {
			relativePath = File.separator + multipartFile3.getName()
					+ File.separator;
		} else if (multipartFile4 != null) {
			relativePath = File.separator + multipartFile4.getName()
					+ File.separator;
		} else if (multipartFile5 != null) {
			relativePath = File.separator + multipartFile5.getName()
					+ File.separator;
		}
		// 得到文件在服务器上的绝对路径
		String uploadPath = request.getSession().getServletContext().getRealPath("file_resource");
		//String uploadPath = FileResUtil.getResourcePath();
		uploadPath += relativePath;
		System.out.println(uploadPath);
		File filePath = new File(uploadPath);
		// 判断文件夹是否存在，如果不存在给与创建出来
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		Resources res = null;
		String newFileName = null;
		if (multipartFile1 != null) {
			res = this.saveFile(multipartFile1, relativePath, uploadPath,
					rUser.getImage01(), request);
			// rUser.setIdcardImg(res.getId());
			// this.rUserService.saveOrUpdate(res);
			// LogUtil.addLog(new LogInfo("添加idcardImg资源数据", rUser.getId(),
			// rUser.getLoginName(), String.valueOf(LogType.ADD.ordinal()),
			// Resources.class.getSimpleName(), res.getId()));
		} else if (multipartFile2 != null) {
			res = this.saveFile(multipartFile2, relativePath, uploadPath,
					rUser.getImage02(), request);
		} else if (multipartFile3 != null) {
			res = this.saveFile(multipartFile3, relativePath, uploadPath,
					rUser.getImage03(), request);
		} else if (multipartFile4 != null) {
			res = this.saveFile(multipartFile4, relativePath, uploadPath,
					rUser.getImage04(), request);
		} else if (multipartFile5 != null) {
			res = this.saveFile(multipartFile5, relativePath, uploadPath,
					rUser.getImage05(), request);
		}
		// this.rUserService.saveOrUpdate(rUser);
		// LogUtil.addLog(new LogInfo("更新" + rUser.getLoginName() + "源数据",
		// rUser.getId(), rUser.getName(),
		// String.valueOf(LogType.UPDATE.ordinal()),
		// rUser.getClass().getSimpleName(),
		// rUser.getId()));
		newFileName = res.getFilePath() + File.separator + res.getId()
				+ res.getExeName();
		Map<String, String> result = new HashMap<String, String>();
		result.put("result", "success");
		result.put("newFileName", newFileName);
		result.put("resId", res.getId());
		out.write(JSONObject.fromObject(result).toString());
		out.flush();
		out.close();
	}

	/**
	 * @description 通过图片id、path清除图片绑定
	 * @author shy
	 * @return
	 * @return String
	 */
	@RequestMapping("/deleteBandingFile")
	@ResponseBody
	public String deleteBandingFile(HttpSession session, String registerId,
			String picId) {
		if (StringUtil.isEmpty(registerId)) {
			this.registerUserService.removeById(Resources.class, picId);
			return Constant.DEL_SUCCESS;
		} else {
			RegisterUser rUser = null;
			RegisterUser temp = this.registerUserService.get(RegisterUser.class,
					registerId);
			if (temp != null) {
				// 清除图片绑定
				if (picId.equals(temp.getImage01())) {
					temp.setImage01("");
				}else if(picId.equals(temp.getImage02())){
					temp.setImage02("");
				}else if(picId.equals(temp.getImage03())){
					temp.setImage03("");
				}else if(picId.equals(temp.getImage04())){
					temp.setImage04("");
				}else if(picId.equals(temp.getImage05())){
					temp.setImage05("");
				}
				this.registerUserService.saveOrUpdate(temp);
				this.registerUserService.removeById(Resources.class, picId);
				rUser = temp;
				session.setAttribute("registerUser", rUser);
				return Constant.DEL_SUCCESS;
			}
		}
		return Constant.UNSUCCESS;
	}

	/**
	 * @description 禁止投标
	 * @author shy
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping("/tenderForbid")
	public void tenderForbid(RegisterUser registerUser, String forbidTime, HttpSession session,HttpServletResponse resp) throws IOException, ParseException {
		String result = "";
		SimpleDateFormat date= new SimpleDateFormat("yyyy-MM-dd");
		Date forbidDate =date.parse(forbidTime);
		registerUser.setForbidEndDate(forbidDate);
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			result = Constant.UNLOGIN;
		} else {

			result = this.registerUserService.tenderforbid(user, registerUser);
		}
		resp.getWriter().print(result);
	}

	/**
	 * @description 恢复投标
	 * @author shy
	 * @throws IOException
	 */
	@RequestMapping("/tenderRecover")
	public void tenderRecover(RegisterUser registerUser, HttpSession session,
			HttpServletResponse resp) throws IOException {
		Map<String, String> map = new HashMap<String, String>();
		String result = "";
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			result = Constant.UNLOGIN;
		} else {

			result = this.registerUserService.tenderRecover(user, registerUser);
		}
		map.put("result", result);
		resp.getWriter().print(JSONObject.fromObject(map).toString());
	}

	/**
	 * @description 获取项目类型
	 * @author shy
	 */
	@RequestMapping("/getProjectCategory")
	@ResponseBody
	public JSONArray listAll() {
		List<ProjectType> list = this.projectTypeService.findAll();
		return JSONArray.fromObject(list);
	}

	/**
	 * @description 进入设置保证金类型页面
	 * @author shy
	 */
	@RequestMapping("/DepositCategoryPage")
	public ModelAndView DepositCategoryPage(String registerId) {
		ModelAndView mv = new ModelAndView("/register/deposit-category");
		List<ProjectType> list = this.projectTypeService.findAll();
		mv.addObject("projectList", list);
		if (!StringUtil.isEmpty(registerId)) {
			String DepositCategoryData = registerUserService
					.getDepositCategory(registerId);
			mv.addObject("DepositCategoryData", DepositCategoryData);
		}
		return mv;
	}

	/**
	 * @description 协议保证金类型设置
	 * @author shy
	 */
	@RequestMapping("/setDepositCategory")
	@ResponseBody
	public String setDepositCategory(HttpServletRequest requset) {
		String DepositCategoryIds = requset.getParameter("DepositCategoryIds");
		String registerId = requset.getParameter("registerId");
		return this.registerUserService.setDepositCategory(DepositCategoryIds,registerId);
	}

	/**
	 * @description  获取服务类型
	 * @author shy
	 */
	@RequestMapping("/getDepositCategory")
	@ResponseBody
	public JSONArray getDepositCategory(HttpServletRequest requset,String regisgerId) {
		List<DepositCategory> list = this.registerUserService.getDepositCategoryById(regisgerId);
		return JSONArray.fromObject(list);
	}


	/**
	 * @description  获取服务类型
	 * @author shy
	 */
	@RequestMapping("/projectCategory")
	@ResponseBody
	public JSONArray getProjectCategory(HttpServletRequest requset,String regisgerId) {
		List<RegisterCategory> list = this.registerUserService.getRegisterCategoryById(regisgerId);
		return JSONArray.fromObject(list);
	}

	/**
	 * @description  注册承诺
	 * @author shy
	 */
	@RequestMapping("/promise")
	@ResponseBody
	public ModelAndView promise(HttpServletRequest requset,String regisgerId) {
		ModelAndView mvAndView = new ModelAndView();
		mvAndView.setViewName("register/promise");
		return mvAndView;
	}

	/**
	 * @description初始化密码
	 * @param registerId
	 * @param requset
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/initializePassword")
	@ResponseBody
	public String initializePassword(String registerId,HttpServletRequest requset,HttpServletResponse response) throws IOException{
		   String result="";
		   RegisterUser rUser = registerUserService.get(RegisterUser.class, registerId);
		   User user =registerUserService.getUserByRegisterId(registerId);
		   String password =  MD5Lock.lock("123456");
		   rUser.setPwd(password);
		   try{
			   if(user!=null){
				   user.setPsw(password);
				   registerUserService.saveOrUpdate(user);
			   }
			   registerUserService.saveOrUpdate(rUser);
			   result=Constant.SAVE_SUCCESS;
		   }catch (Exception e){
			   e.printStackTrace();
			   result=Constant.SAVE_UN_SUCCESS;
		   }
		  return result;

	}

	/**
	 * @description 删除投标人
	 * @param registerId
	 * @return
	 */
	@RequestMapping("/deleteUser")
	@ResponseBody
	public String deleteUser(String registerId){
		   String result="";
		   RegisterUser rUser = registerUserService.get(RegisterUser.class, registerId);
		   User user =registerUserService.getUserByRegisterId(registerId);
		   rUser.setRemoveFlag(1);
		   try {
			   if(user!=null){
				   user.setFlag(1);
				   registerUserService.saveOrUpdate(user);
			   }
			   registerUserService.saveOrUpdate(rUser);
			   result=Constant.SAVE_SUCCESS;
		} catch (Exception e) {
			   e.printStackTrace();
			   result=Constant.SAVE_UN_SUCCESS;
		}
		return result;
	}

	/**
	 * @description 封存投标人
	 * @param registerId
	 * @return
	 */
	@RequestMapping("/sealUpUser")
	@ResponseBody
	public String sealUpUser(String registerId){
		String result="";
		RegisterUser rUser = registerUserService.get(RegisterUser.class, registerId);
        if (rUser.getRemoveFlag() == 2) {
            return "该用户已被封存,无需再次操作!";
        }
		User user =registerUserService.getUserByRegisterId(registerId);
		rUser.setRemoveFlag(2); //removeFlag =2 时 封存用户
		try {
			if(user!=null){
				user.setFlag(2);//removeFlag =2 时 封存用户
				registerUserService.saveOrUpdate(user);
			}
			registerUserService.saveOrUpdate(rUser);
			result=Constant.SAVE_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			result=Constant.SAVE_UN_SUCCESS;
		}
		return result;
	}
}
